<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params" v-show="formVisible">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          :auto-top="1"
          clearable
          :bottom-level="2"
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="loanBehStatusSelected"
          placeholder="项目状态选择"
          clearable
          number-key
          :options="{ 0: '在保项目', 1: '解保项目' }"
          @change="handleStatusChange"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-org-bank
          v-model="params['bank_id.eq']"
          placeholder="选择银行"
          @change="getData()"
          filterable
          clearable
          class="form-control-ml"
        ></select-org-bank>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="放款开始日期"
          end-placeholder="放款结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params['gua_type.eq']"
          :options="enumGuatype"
          placeholder="业务模式"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params['project_type.eq']"
          :options="enumProjectType"
          placeholder="业务类型"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="handlerEdit()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-upload2" @click="importVisible = true">导入台账</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-upload2" @click="importPlanVisible = true">导入还款计划</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel(innterTitle)"
        >
          台账下载
        </el-button>
      </el-form-item>
    </el-form>

    <!-- <h4 class="text-center font-weight-bold">{{innterTitle}}</h4> -->
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:warranty_method="scope">
        <el-tooltip effect="light" :content="scope.row.warranty_method" placement="bottom">
          <span>{{ scope.row.warranty_method | substr(19) }}</span>
        </el-tooltip>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <import-excel
      :title="importTitle"
      :visible.sync="importVisible"
      :post-api="importUrl"
      :excel-template="importFileUrl"
      @success="getData(params.index)"
    ></import-excel>

    <import-excel
      title="导入还款计划"
      :visible.sync="importPlanVisible"
      :post-api="importPlanUrl"
      :excel-template="importPlanFileUrl"
      @success="getData(params.index)"
    ></import-excel>

    <repay-dialog
      :visible.sync="replayVisible"
      :query-id="replayId"
      @success="getData(params.index)"
    ></repay-dialog>

    <ledger-edit
      :visible.sync="editVisible"
      :table-id="tableId"
      :form-data="formData"
      @success="getData(params.index)"
    ></ledger-edit>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  ledgerTableColumns,
  reportDataAdapter,
  enumGuatype,
} from '@/credit/views/city/reportCity/reportMixins'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
import { lastPickerShortcuts, nextPickerShortcuts } from '@/common/plugins/tools/date'
import { queryTrouble } from '@vimi/utils-api'

import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import ImportExcel from '@/components/ImportExcel'
import SelectAddress from '@/components/select/SelectAddress'
import RepayDialog from '@/credit/views/city/self/after/repay/RepayDialog'
import LedgerEdit from '@/credit/views/city/reportCity/ledger/component/LedgerEdit'
import { enumProjectType } from '@/bigcredit/views/program/enum'
export default {
  components: {
    SelectOrgBank,
    ImportExcel,
    SelectAddress,
    RepayDialog,
    LedgerEdit,
  },
  props: {
    reportType: Number,
    formVisible: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      enumGuatype,
      enumProjectType,
      loading: false,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'service_id.eq': '',
        'bank_id.eq': '',
        // 'is_submit_report.eq': 0,
        // 'gua_type.neq': 3,
      },
      order: {
        create_time: 'desc',
      },
      tableName: 'market_project',
      totalCount: 0,
      tableData: [],
      tableColumns: [
        ...ledgerTableColumns,
        {
          attrs: { label: '操作', align: 'center', width: 100, fixed: 'right' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handlerEdit,
              ifRender: row => +row.is_history === 1,
            },
            {
              content: '还款跟踪',
              icon: 'fa fa-credit-card',
              event: this.handlerRepay,
            },
          ],
        },
      ],

      loanBehStatusSelected: '',
      datePicked: [],
      pickerOptions: {
        shortcuts: [...lastPickerShortcuts, ...nextPickerShortcuts],
      },

      importUrl: '',
      importPlanUrl: '',
      importKey: 'customer_report_template',
      importTitle: '导入市场化项目台账',
      importVisible: false,
      importPlanVisible: false,

      exportLoading: false,

      replayVisible: false,
      replayId: '',

      formData: {},
      tableId: '',
      editVisible: false,
    }
  },
  computed: {
    ...mapGetters(['org', 'clientId']),
    innterTitle() {
      return this.org.orgName + '存量业务项目台账表'
    },
    importFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/市场化项目台账导入模板.xlsx?${+new Date()}`
    },
    importPlanFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/还款计划导入模板.xlsx?${+new Date()}`
    },
  },
  watch: {},
  created() {
    this.importUrl =
      '/api/credit/import/' +
      queryTrouble('market_project', {
        importKey: this.importKey,
        'service_id.eq': this.clientId,
      })
    this.importPlanUrl =
      '/api/credit/import/' +
      queryTrouble('datum_repay_list', {
        importKey: 'datum_repay_list_template',
      })

    this.params['service_id.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    handlerEdit(row) {
      this.editVisible = true
      this.tableId = row.customer_related_id || ''
      this.formData = { ...row }
    },
    handlerRepay(row = {}) {
      this.replayId = row.customer_related_id || ''
      this.replayVisible = true
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.fetchData(this.params)
      this.loading = false
      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(reportDataAdapter)
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    handleDateChange() {
      this.params.index = 1
      if (this.datePicked && this.datePicked.length === 2) {
        this.params['load_date.gte'] = this.datePicked[0]
        this.params['load_date.lte'] = `${this.datePicked[1]} 23:59:59`
      } else {
        this.params['load_date.gte'] = ''
        this.params['load_date.lte'] = ''
      }
      this.getData()
    },
    handleStatusChange() {
      switch (this.loanBehStatusSelected) {
        case 0:
          this.params['load_beh_status.neq'] = 6
          this.params['load_beh_status.eq'] = ''
          break
        case 1:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = 6
          break
        default:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = ''
          break
      }
      this.getData()
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.params,
        dataAdapter: reportDataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
    handleUpload() {},
  },
}
</script>

<style lang="scss" scoped></style>
